//一：给页面注入js，让页面响应插件发送过去的消息
var myScript = document.createElement("script");
myScript.append('window.addEventListener("message", async function (event) {    if (event.data.from === "extenstion" && event.data.action == "telemetry") {        var message = {"from": "web", "action": "telemetry", "data": window.bmak.get_telemetry()};        window.postMessage(message, "*");    }    if (event.data.from === "extenstion" && event.data.action == "localStorage") {        var message = {            "from": "web",            "action": "localStorage",            "key": event.data.data,            "data": window.localStorage.getItem(event.data.data)        };        window.postMessage(message, "*");    }    if (event.data.from === "extenstion" && event.data.action == "localStorage_del") {        window.localStorage.removeItem(event.data.data);        window.postMessage(message, "*");    }    if (event.data.from === "extenstion" && event.data.action == "link") {        window.location = event.data.data;    }});');
document.body.append(myScript);
//二：myscript.js 通过window.postMessage 发送消息到页面,要用到页面的环境才能获取到的数据时，可以通过该方式，用注入的js进行处理
// var message = { "from": "extenstion", "action":"telemetry" };
// window.postMessage(message, "*");

//拦截页面的请求，获取返回数据
var injectedJs = document.createElement('script');
injectedJs.src = chrome.runtime.getURL('injected.js');
injectedJs.onload = function () {
    this.remove();
};
(document.head || document.documentElement).appendChild(injectedJs);

function ajax(url, data, options, success, error) {
    let operation = Object.assign({
        contentType: "application/json;charset=utf-8",
        method: "get",
        dataType: "json",
        async: true
    }, options);

    $.ajax({
        url: url,
        contentType: operation.contentType,
        data: data,
        async: operation.async,
        type: operation.method,
        dataType: operation.dataType,
        success: function (res) {
            if (success) {
                success(res);
            }
        },
        error: function (xhr, errorMessage, e) {
            if (error) {
                error(xhr, errorMessage, e);
            } else {
                console.log(e)
            }
        }
    })
}

window.ajax = ajax;

function localTimeFunction(callback, sec) {
    return new Promise((resolve) => setTimeout(function () {
        callback()
        resolve(true)
    }, sec))
}